/*
 * @Author: huangyq
 * @Date: 2022-04-20 14:15:44
 * @LastEditTime: 2023-12-06 10:18:36
 * @LastEditors: hyq
 * @Description: 权限
 * @FilePath: /vue3-boilerplate-pc-client/src/stores/permission.ts
 */
import { defineStore, acceptHMRUpdate } from 'pinia'
import { RouteRecordRaw } from 'vue-router'
import { RoleApi } from '@/apis'
import routes from '@/routers/routes'

interface IPermissionState {
  codes: string[]
  effectiveRouters: RouteRecordRaw[]
}

// 白名单
const whiteList: string[] = ['000']
const codeMap = new Map<string, number>()
whiteList.map(item => codeMap.set(item, 1))

export const usePermissionStore = defineStore('permission', {
  state: (): IPermissionState => {
    return {
      codes: [],
      effectiveRouters: []
    }
  },
  actions: {
    /**
     * 获取权限
     */
    async fetchPermission() {
      const res = await RoleApi.permissionUsingGet({})
      if (res.data.success) {
        const list: string[] = (res.data.permissions as unknown[]).map(
          (item: any) => item.code
        )
        this.setPermissionCode(list)
        this.setEffectiveRouters()
      }
    },

    /**
     * 设置权限
     * @param codes
     */
    setPermissionCode(codes: string[]) {
      this.codes = codes
      codes.map((item: string) => codeMap.set(item, 1))
    },

    /**
     * 设置有效的路由
     * @param code
     * @returns
     */
    setEffectiveRouters() {
      const checkRoutes =
        routes.find(item => item.name === 'pages')?.children || []
      this.effectiveRouters = findEffectiveRouters(checkRoutes)
    },

    /**
     * 检测是否有权限
     * @param code
     * @returns
     */
    checkPermissionByCode(code: string) {
      return codeMap.get(code) === 1
    }
  }
})

/**
 * 查找有权限的路由
 * @param routes
 * @returns
 */
function findEffectiveRouters(routes: RouteRecordRaw[]) {
  const effectiveRouters: RouteRecordRaw[] = []
  let start = 0
  const end = routes.length - 1
  while (start <= end) {
    const checkRoute = routes[start]
    if (checkRoute.children && checkRoute.children.length > 0) {
      routes[start].children = findEffectiveRouters(routes[start].children!)
    }
    if (codeMap.get(checkRoute.meta?.code as string) === 1) {
      effectiveRouters.push(checkRoute)
    }
    start++
  }
  return effectiveRouters
}

// hmr
if (import.meta.hot) {
  import.meta.hot.accept(
    acceptHMRUpdate(usePermissionStore as any, import.meta.hot)
  )
}
